"use client";
import { Camera, LoaderIcon, Mail } from "lucide-react";
import Form from "./_components/form";
import dayjs from "dayjs";
import { useMutation, useQuery } from "@tanstack/react-query";
import Upload from "@/components/custom-ui/upload";
import { toast } from "sonner";
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import UserAvatar from "@/components/custom-ui/user-avatar";
import { getProfileAction } from "@/actions/profile";
import { UploadAction } from "@/actions/file";

export default function Page() {
  const { data: session, update } = useSession();
  const [fileId, setFileId] = useState("");
  const t = useTranslations("profilePages");

  const userQuery = useQuery({
    queryKey: ["getUserByUserId", session?.user.id ?? ""],
    queryFn: async ({ queryKey }) => {
      const [, id] = queryKey;
      return await getProfileAction({ id })
    },
    enabled: !!(session?.user.id ?? ""),
    retry: 2,
  });

  useEffect(() => {
    if (userQuery.data?.image) {
      setFileId(userQuery.data.image);
    }
  }, [userQuery.data?.image]);

  const uploadMutation = useMutation({
    mutationFn: async ({ files }: { files: FileList }) => {
      return await UploadAction(files);
    },
    onSuccess: (data) => {
      if (data) {
        toast.success("Upload success");
      } else {
        toast.error("Upload failed");
      }
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  const handleUpload = async (files: FileList) => {
    const fileId = await uploadMutation.mutateAsync({ files });
    if (fileId) {
      await update({ image: fileId });
      setFileId(fileId);
    }
  };

  return (
    <>
      {userQuery.isPending ? (
        <div className="w-full h-full flex justify-center items-center">
          <LoaderIcon className="animate-spin" />
        </div>
      ) : (
        <>
          <div className="flex flex-col sm:flex-row gap-6 w-full">
            <div className="flex items-center justify-center">
              <div className="h-24 w-24 relative">
                <UserAvatar
                  defaultIconSize="h-8 w-8"
                  className="h-24 w-24 bg-foreground/5 shadow-[0_0_10px_2px_rgba(0,0,0,0.2)] hover:shadow-[0_0_20px_2px_rgba(0,0,0,0.2)] cursor-pointer"
                />
                <Upload
                  handleUpload={handleUpload}
                  disabled={uploadMutation.isPending}
                >
                  <div className="absolute right-0 bottom-0 h-8 w-8 rounded-full text-primary hover:text-primary/60 bg-primary-foreground flex items-center justify-center cursor-pointer border border-primary/10">
                    {!uploadMutation.isPending ? (
                      <Camera size={16} />
                    ) : (
                      <LoaderIcon className="animate-spin" size={16} />
                    )}
                  </div>
                </Upload>
              </div>
            </div>
            <div className="flex-1 flex flex-col h-24 justify-center items-center sm:items-start">
              <h1 className="flex flex-row gap-2 text-2xl font-bold">
                <div className="flex items-center">
                  <Mail className="size-4" />
                </div>
                {userQuery.data?.email ?? "----"}
              </h1>
              <p className="text-muted-foreground text-sm">
                {t("createdAt")}{" "}
                {userQuery.data?.createdAt
                  ? dayjs(userQuery.data?.createdAt).format(
                    "YYYY-MM-DD HH:mm:ss"
                  )
                  : "----"}
              </p>
            </div>
          </div>

          <div className="flex gap-4 w-full">
            <Form data={userQuery.data} fileId={fileId} />
          </div>
        </>
      )}
    </>
  );
}
